<template>
  <div class="register-container">
    <div class="register-wrapper">
      <div class="welcome-section">
        <h1 class="welcome-title">创建账户</h1>
        <p class="welcome-subtitle">加入我们的平台</p>
        <div class="brand-logo">
          <el-icon :size="42" color="#ffffff">
            <Grid />
          </el-icon>
          <span class="brand-name">系统管理平台</span>
        </div>
      </div>
      <div class="form-section">
        <RegisterForm @submit="handleRegisterSubmit" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ElNotification } from 'element-plus'
  import RegisterForm from '@/components/RegisterForm.vue'
  import { Grid } from '@element-plus/icons-vue'
  import { registerUser } from '@/api/userApi' // 导入注册API
  import router from '@/router'

  // 处理注册提交
  const handleRegisterSubmit = async (registerData: { account: string; username: string; password: string }) => {
    try {
      // 调用实际的注册API
      const response = await registerUser(registerData.account, registerData.username, registerData.password)

      ElNotification.success({
        title: '注册成功',
        message: `欢迎 ${registerData.username}，请登录您的账户`,
        duration: 3000,
      })

      // 注册成功清楚localStorage
      console.log('注册成功，清除localStorage')
      localStorage.clear()

      // 注册成功后跳转到登录页，并将注册的账号作为查询参数传递
      router.push({
        path: '/login',
        query: { account: registerData.account },
      })
      console.log('注册响应:', response)
    } catch (error: unknown) {
      let errorMessage = '注册失败'
      let errorCode = 0

      if (error instanceof Error) {
        console.error('注册错误详情:', {
          message: error.message,
          stack: error.stack,
          response: (error as any).response,
        })

        if ((error as any).response) {
          // 后端返回了具体的错误信息
          const axiosError = error as { response?: { status: number; data: { code?: number; message?: string } } }

          if (axiosError.response?.data) {
            errorCode = axiosError.response.data.code || axiosError.response.status
            errorMessage = axiosError.response.data.message || getStandardErrorMessage(errorCode)
          } else {
            // 没有响应数据，使用标准HTTP状态码解释
            errorCode = axiosError.response?.status || 0
            errorMessage = getStandardErrorMessage(errorCode)
          }
        } else if ((error as any).request) {
          // 请求已发出但未收到响应
          errorMessage = '无法连接服务器，请检查网络或稍后再试'
        } else {
          // 其他类型的错误
          errorMessage = error.message
        }
      } else {
        // 非标准错误对象
        errorMessage = '发生未知错误，请检查网络或重试'
      }

      ElNotification.error({
        title: '注册失败',
        message: `${errorMessage} (错误代码: ${errorCode || 'N/A'})`,
        duration: 4000,
      })
    }
  }

  /**
   * 获取标准HTTP错误消息
   * @param errorCode HTTP状态码或自定义错误码
   * @returns 对应的错误消息
   */
  function getStandardErrorMessage(errorCode: number): string {
    switch (errorCode) {
      case 200:
        return 'OK'
      case 400:
        return '请求参数错误，请检查输入内容'
      case 409:
        return '手机号已被注册'
      case 1001:
        return '该手机号已注册'
      case 500:
        return '服务器内部错误，请联系管理员或稍后再试'
      default:
        return '发生错误，请检查网络或稍后再试'
    }
  }
</script>

<style scoped>
  .register-container {
    height: 100vh;
    background-color: #f0f8ff;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .register-wrapper {
    background-color: white;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    display: flex;
    width: 90%;
    max-width: 1200px;
    min-height: 650px;
    overflow: hidden;
  }

  .welcome-section {
    flex: 1;
    padding: 80px 20px 80px 60px;
    background: linear-gradient(135deg, #1e90ff 0%, #74b9ff 100%);
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .welcome-title {
    font-size: 2.5rem;
    margin-bottom: 20px;
    font-weight: 700;
  }

  .welcome-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
    margin-bottom: 40px;
  }

  .brand-logo {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 60px;
  }

  .brand-name {
    font-size: 1.8rem;
    font-weight: 700;
  }

  .form-section {
    flex: 1.5;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  @media (max-width: 768px) {
    .register-wrapper {
      flex-direction: column;
    }

    .welcome-section {
      padding: 40px 20px;
      text-align: center;
    }

    .brand-logo {
      justify-content: center;
    }
  }
</style>
